<template>
  <view class="container">
    <!-- 订单状态标签栏 -->
    <view class="tab-bar">
      <view
        class="tab-item"
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.type }"
        @tap="switchTab(tab.type)"
      >
        <text>{{ tab.name }}</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      scroll-y
      class="order-list"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      @refresherrefresh="refresh"
    >
      <view class="order-item" v-for="order in orderList" :key="order.id">
        <view class="order-header">
          <text class="order-no">订单号：{{ order.orderNo }}</text>
          <text class="order-status">{{ order.statusText }}</text>
        </view>

        <view class="goods-list">
          <view
            class="goods-item"
            v-for="goods in order.goodsList"
            :key="goods.id"
            @tap="navToDetail(goods.spuId)"
          >
            <image :src="goods.image" mode="aspectFill" class="goods-image" />
            <view class="goods-info">
              <text class="goods-name">{{ goods.name }}</text>
              <text class="goods-spec">{{ goods.specText }}</text>
              <view class="goods-price-wrap">
                <text class="goods-price">¥{{ goods.price }}</text>
                <text class="goods-count">x{{ goods.count }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="order-footer">
          <view class="total">
            共{{ order.totalCount }}件商品 合计：
            <text class="price">¥{{ order.totalAmount }}</text>
          </view>

          <view class="btn-group">
            <button
              class="btn"
              v-if="order.status === 'unpaid'"
              @tap="handlePay(order)"
            >
              立即付款
            </button>

            <button
              class="btn"
              v-if="order.status === 'unreceived'"
              @tap="handleConfirm(order)"
            >
              确认收货
            </button>

            <button
              class="btn outline"
              v-if="order.status === 'completed'"
              @tap="navToComment(order)"
            >
              评价
            </button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="orderList.length === 0">
        <image src="/static/order-icons/empty-order.png" mode="aspectFit" />
        <text>暂无相关订单</text>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus" />
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { orderService } from "@/services/order";
import { payService } from "@/services/pay";

// 标签页配置
const tabs = [
  { name: "全部", type: "all", status: null },
  { name: "待付款", type: "unpaid", status: 0 },
  { name: "待发货", type: "unshipped", status: 1 },
  { name: "待收货", type: "unreceived", status: 2 },
  { name: "待评价", type: "evaluating", status: 3 },
  { name: "已完成", type: "completed", status: 5 },
];

// 响应式数据
const currentTab = ref("all");
const orderList = ref([]);
const page = ref(1);
const loadMoreStatus = ref("more");

// 获取订单列表
const getOrderList = async (reset = false) => {
  try {
    if (reset) {
      page.value = 1;
      orderList.value = [];
    }

    loadMoreStatus.value = "loading";
    const currentTabObj = tabs.find((tab) => tab.type === currentTab.value);

    // 准备请求参数
    const params = {
      pageIndex: page.value,
      pageSize: 10,
    };

    // 只有当status不为null时才添加到请求参数中
    if (currentTabObj.status !== null) {
      params.status = Number(currentTabObj.status);
    }

    const res = await orderService.getOrderList(params);

    console.log("res", res);

    // 检查返回的数据结构
    if (res.items) {
      // 处理订单数据
      const formattedOrders = res.items.map((order) => ({
        id: order.id,
        orderNo: order.orderNo,
        status: getOrderStatus(order.status),
        statusText: getStatusText(order.status),
        totalCount: order.items.length,
        totalAmount: (order.totalAmount / 100).toFixed(2),
        goodsList: order.items.map((item) => ({
          id: item.id,
          spuId: item.spuId,
          name: item.goodTitle,
          image: item.primaryImage,
          specText: item.specValues,
          price: (item.salePrice / 100).toFixed(2),
          count: item.quantity,
        })),
      }));

      console.log("formattedOrders", formattedOrders);

      if (reset) {
        orderList.value = formattedOrders;
      } else {
        orderList.value = [...orderList.value, ...formattedOrders];
      }

      // 判断是否有更多数据
      const { total, pageSize } = res;
      loadMoreStatus.value = total > page.value * pageSize ? "more" : "noMore";
      page.value++;
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    loadMoreStatus.value = "more";
  }
};

// 获取订单状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return "待付款";
    case 1:
      return "待发货";
    case 2:
      return "待收货";
    case 3:
      return "待评价";
    case 4:
      return "已取消";
    case 5:
      return "已完成";
    default:
      return "未知状态";
  }
};

// 获取订单状态类型
const getOrderStatus = (status) => {
  switch (status) {
    case 0:
      return "unpaid";
    case 1:
      return "unshipped";
    case 2:
      return "unreceived";
    case 3:
      return "evaluating";
    case 4:
      return "cancelled";
    case 5:
      return "completed";
    default:
      return "unknown";
  }
};

// 切换标签
const switchTab = (type) => {
  currentTab.value = type;
  getOrderList(true);
};

// 下拉刷新
const refresh = async () => {
  await getOrderList(true);
  uni.stopPullDownRefresh();
};

// 加载更多
const loadMore = () => {
  if (loadMoreStatus.value === "more") {
    getOrderList();
  }
};

// 支付订单
const handlePay = async (order) => {
  uni.showLoading({
    title: "正在支付...",
    mask: true,
  });

  try {
    // 使用 payService 的统一支付接口
    const res = await payService.payOrder(order.orderNo, {
      orderNo: order.orderNo,
      amount: Math.round(order.totalAmount * 100), // 转换为分，确保是整数
      total_fee: Math.round(order.totalAmount * 100), // 微信支付JSAPI必需参数
      description: `订单${order.orderNo}支付`
    });

    // 先关闭loading，避免支付窗口与loading重叠
    uni.hideLoading();

    if (res.success && res.data) {
      try {
        // 使用 payService 的微信支付方法
        await payService.wxPay(res.data);

        // 支付成功
        uni.showToast({
          title: "支付成功",
          icon: "success",
        });

        // 刷新订单列表
        await getOrderList(true);
      } catch (payError) {
        // 处理支付过程中的错误
        if (payError.message === '用户取消支付') {
          uni.showToast({
            title: "已取消支付",
            icon: "none",
          });
        } else {
          uni.showToast({
            title: payError.message || "支付失败",
            icon: "none",
          });
          console.error("支付过程错误:", payError);
        }
      }
    } else {
      uni.showToast({
        title: res.message || "获取支付参数失败",
        icon: "none",
      });
    }
  } catch (error) {
    // 处理网络请求错误
    console.error("支付接口调用失败:", error);
    uni.showToast({
      title: "支付失败，请稍后重试",
      icon: "none",
    });
    uni.hideLoading(); // 确保loading被关闭
  }
};

// 确认收货
const handleConfirm = (order) => {
  uni.showModal({
    title: "提示",
    content: "确认已收到商品？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await orderService.confirmOrder(order.id);
          if (res.success) {
            uni.showToast({
              title: "确认成功",
              icon: "success",
            });
            refresh();
          }
        } catch (error) {
          console.error("确认收货失败:", error);
          uni.showToast({
            title: "确认失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 页面跳转
const navToDetail = (spuId) => {
  uni.navigateTo({
    url: `/pages/goods/detail?spuId=${spuId}`,
  });
};

const navToComment = (order) => {
  uni.navigateTo({
    url: `/pages/order/comment?orderId=${order.id}`,
  });
};

// 生命周期
onLoad((options) => {
  if (options.type) {
    currentTab.value = options.type;
  }
});

onMounted(() => {
  getOrderList(true);
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f8f8;

  .tab-bar {
    display: flex;
    background-color: #fff;
    padding: 0 20rpx;
    position: sticky;
    top: 0;
    z-index: 1;

    .tab-item {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #333;
      position: relative;

      &.active {
        color: #ff4444;
        font-weight: bold;

        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #ff4444;
          border-radius: 2rpx;
        }
      }
    }
  }

  .order-list {
    height: calc(100vh - 80rpx);

    .order-item {
      margin: 20rpx;
      background-color: #fff;
      border-radius: 12rpx;
      overflow: hidden;

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        border-bottom: 2rpx solid #f5f5f5;

        .order-no {
          font-size: 24rpx;
          color: #999;
        }

        .order-status {
          font-size: 26rpx;
          color: #ff4444;
        }
      }

      .goods-list {
        padding: 20rpx;

        .goods-item {
          display: flex;
          margin-bottom: 20rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .goods-image {
            width: 160rpx;
            height: 160rpx;
            border-radius: 8rpx;
          }

          .goods-info {
            flex: 1;
            margin-left: 20rpx;

            .goods-name {
              font-size: 28rpx;
              color: #333;
              margin-bottom: 10rpx;
            }

            .goods-spec {
              font-size: 24rpx;
              color: #999;
              margin-bottom: 10rpx;
            }

            .goods-price-wrap {
              display: flex;
              justify-content: space-between;
              align-items: center;

              .goods-price {
                font-size: 28rpx;
                color: #ff4444;
              }

              .goods-count {
                font-size: 24rpx;
                color: #999;
              }
            }
          }
        }
      }

      .order-footer {
        padding: 20rpx;
        border-top: 2rpx solid #f5f5f5;

        .total {
          text-align: right;
          font-size: 26rpx;
          color: #666;
          margin-bottom: 20rpx;

          .price {
            font-size: 32rpx;
            color: #ff4444;
            font-weight: bold;
          }
        }

        .btn-group {
          display: flex;
          justify-content: flex-end;

          .btn {
            margin-left: 20rpx;
            width: 160rpx;
            height: 60rpx;
            line-height: 60rpx;
            text-align: center;
            font-size: 26rpx;
            border-radius: 30rpx;
            background-color: #ff4444;
            color: #fff;

            &.outline {
              background-color: #fff;
              color: #ff4444;
              border: 2rpx solid #ff4444;
            }
          }
        }
      }
    }

    .empty {
      padding: 100rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;

      image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
      }

      text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}
</style>
